package com.rjhch.hadoopTest.mr.phoenix;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * phoenix中插入数据mapreduce任务
 */
public class UpsertMR {
    private static final Log log = LogFactory.getLog(UpsertMR.class);
    private static FileSystem hdfs;

    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);

        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            String sql = value.toString();
//            String command = "echo \"" + sql + "\" | sqlline.py";
            String command = "psql.py " + sql;
            log.info("command: " + command);
            String[] commands = { "/bin/sh", "-c", command };
            Process process = Runtime.getRuntime().exec(commands);

            final BufferedReader readStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 获取错误输出
            final BufferedReader readStderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            // 创建线程执行
            Thread execThread = new Thread() {
                String tmp1;
                String tmp2;

                public void run() {
                    try {
                        // 逐行读取
                        while ((tmp1 = readStdout.readLine()) != null || (tmp2 = readStderr.readLine()) != null) {
                            if (tmp1 != null) {
                                log.debug(tmp1);
                            }
                            if (tmp2 != null) {
                                log.error(tmp2);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            execThread.start();
            context.write(new Text(sql), one);
            process.waitFor();
        }
    }

    public static class IntSumReducer
            extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    /**
     * 登录hdfs
     */
    private static void login() throws Exception {
        if (UserGroupInformation.isSecurityEnabled()) {
            String keytabFile;
            if (System.getProperty("os.name").startsWith("Windows")) {
                keytabFile = "D:\\keytab\\hadoop.keytab";
            } else {
                keytabFile = "/etc/security/keytab/hadoop.keytab";
            }
            log.info("keytabFile: " + keytabFile);
            UserGroupInformation.loginUserFromKeytab("hadoop/hadoop01@HADOOP.COM", keytabFile);
            log.info("login success with user: hadoop");
        }
    }

    public static void main(String[] args) throws Exception {
        login();
        Configuration conf = new Configuration();
        hdfs = FileSystem.get(conf);
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length < 1) {
            System.err.println("Usage: UpsertMR <in> [<in>...]");
            System.exit(2);
        }
        Job job = Job.getInstance(conf, "phoenix upsert");
        job.setJarByClass(UpsertMR.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        for (int i = 0; i < otherArgs.length; ++i) {
            FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
        }
        String outputPathString = "/tmp/phoenix/upsert";
        Path outputPath = new Path(outputPathString);

        FileOutputFormat.setOutputPath(job, outputPath);
        if (hdfs.exists(outputPath)) {
            hdfs.delete(outputPath, true);       //删除脏输出目录
        }

        TextInputFormat.setMinInputSplitSize(job,300);      //只保存了文件名
        TextInputFormat.setMaxInputSplitSize(job,300);
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
